package com.example.webpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.webpractice.dao.TokenDao;
import com.example.webpractice.po.TokenPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Service("TokenService")
public class TokenService {

    @Autowired
    private TokenDao dao;

    public TokenPO getTokenEntity(String token) {

        TokenPO tokenPO = dao.selectOne(new QueryWrapper<TokenPO>().eq("token", token));
        if (tokenPO == null || tokenPO.getExpiratedtime().getTime() < new Date().getTime()) {
            return null;
        }
        return tokenPO;
    }


    public String generateToken(Long userid, String username, String tableName, String role) {
        TokenPO tokenEntity = dao.selectOne(new QueryWrapper<TokenPO>().eq("userid", userid).eq("role", role));
        String token = genToken();
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR_OF_DAY, 1);
        if (tokenEntity != null) {
            tokenEntity.setUsername(username);
            tokenEntity.setToken(token);
            tokenEntity.setExpiratedtime(cal.getTime());
            dao.updateById(tokenEntity);
        } else {
            dao.insert(new TokenPO(userid, username, tableName, role, token, cal.getTime()));
        }
        return token;
    }

    public String genToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
